<template>
  <div>
    <div class="table-page-search-wrapper">
      <a-row type="flex" justify="space-between" align="middle">
        <a-col :span="23">
          <a-form layout="inline" :model="listQuery">
            <a-form-item label="存储配置">
              <a-select
                v-model:value="listQuery.ps_id"
                placeholder="请选择"
                style="width: 160px"
                allowClear
              >
                <a-select-option key="" value=""> 全部配置 </a-select-option>
                <a-select-option v-for="d in allServer" :key="d._id" :value="d._id">
                  {{ d.title }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="存储分类">
              <a-select
                v-model:value="listQuery.fc_id"
                placeholder="请选择"
                style="width: 160px"
                allowClear
              >
                <a-select-option key="" value=""> 全部分类 </a-select-option>
                <a-select-option v-for="d in allCate" :key="d._id" :value="d._id">
                  {{ d.title }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="上传时间">
              <a-range-picker
                v-model:value="listQuery.send_time_range"
                show-time
                :presets="rangePresets"
                :disabled="listQuery.title.length > 0"
                style="width: 370px"
              />
            </a-form-item>
            <a-form-item label="搜索项">
              <a-tooltip title="输入文件ID/标题搜索，搜索时【上传时间】参数不生效">
                <a-input
                  v-model:value="listQuery.title"
                  placeholder="输入文件ID/标题搜索..."
                  allowClear
                />
              </a-tooltip>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="searchSubmit"> 搜索 </a-button>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="1">
          <div style="margin-right: 0px; float: right; display: flex; align-item: center">
            <a-tooltip placement="top">
              <template #title>
                <span>刷新列表</span>
              </template>
              <a-button @click="reloadList">
                <template #icon>
                  <SyncOutlined />
                </template>
              </a-button>
            </a-tooltip>
          </div>
        </a-col>
      </a-row>
    </div>
    <div style="display: flex; align-items: center; justify-content: start">
      <a-button
        :disabled="selectedRowKeys.length == 0 ? true : false"
        style="margin-right: 10px"
        @click="copyImgUrl"
        >仅复制链接</a-button
      >
      <a-tooltip title="仅图片文件可生成代码">
        <a-button
          :disabled="selectedRowKeys.length == 0 ? true : false"
          style="margin-right: 10px"
          @click="copyImgHtml"
          >复制代码</a-button
        >
      </a-tooltip>
      <a-tooltip title="使用本功能前请确保已将 console.21ds.cn 添加至白名单">
        <a-button
          :disabled="selectedRowKeys.length == 0 ? true : false"
          style="margin-right: 10px"
          @click="downloadSelect"
          >下载所选</a-button
        >
      </a-tooltip>
      <a-button
        v-permission="{ action: 'del_file_batch' }"
        :disabled="selectedRowKeys.length == 0 ? true : false"
        danger
        style="margin-right: 10px"
        @click="deleteSelect"
        >删除所选</a-button
      >
      <a-button :disabled="dataList.data.length == 0" style="margin-right: 10px" @click="SelectAll"
        >全选本页</a-button
      >
      <a-button
        :disabled="selectedRowKeys.length == 0 ? true : false"
        style="margin-right: 10px"
        @click="unSelect"
        >取消选择</a-button
      >
      <div v-if="selectedRowKeys.length > 0">已选择文件: {{ selectedRowKeys.length }}</div>
    </div>
    <a-divider />
    <Empty
      v-if="dataList.data.length == 0"
      image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original"
      :image-style="{
        height: '120px'
      }"
    >
      <template #description>
        <span> 暂无文件 </span>
      </template>
    </Empty>
    <a-checkbox-group v-model:value="selectedRowKeys">
      <div class="fileList">
        <div v-for="(item, index) in dataList.data" :key="index">
          <a-tooltip>
            <template #title>
              <span> 文件ID：{{ item._id }} </span> <br />
              <span> 文件名：{{ item.name }} </span> <br />
              <span>所属配置：{{ item.fs_title }}</span> <br />
              <span>所属分类：{{ item.fc_title || '' }}</span> <br />
              <span v-if="item.size_mb >= 1"> 文件大小：{{ item.size_mb }}MB </span>
              <span v-else> 文件大小：{{ item.size_kb }}KB </span>
            </template>
            <div
              class="fileItem"
              :class="inArray(item._id, selectedRowKeys) ? ' div_selected ' : ' div_unselected '"
            >
              <a-tooltip :title="item.platform_title">
                <img
                  :src="item.platform_icon_url"
                  style="
                    position: absolute;
                    top: 0px;
                    left: 3px;
                    z-index: 99;
                    width: 22px;
                    height: 22px;
                  "
                />
              </a-tooltip>
              <a-checkbox
                :value="item._id"
                style="position: absolute; top: 0px; right: 3px; z-index: 99; zoom: 1.2"
              />
              <a-image
                v-if="item.file_type == 'img'"
                :key="index"
                :width="140"
                style="max-height: 140px"
                :src="item.icon_url"
                fallback=""
              />
              <img
                v-else-if="item.file_type == 'office'"
                :src="item.icon_url"
                style="
                  cursor: pointer;
                  width: 98px;
                  max-height: 98px;
                  margin-left: 17px;
                  margin-bottom: 16px;
                "
                @click="viewOffice(item.url)"
              />
              <img
                v-else-if="item.file_type == 'iframe'"
                :src="item.icon_url"
                style="
                  cursor: pointer;
                  width: 98px;
                  max-height: 98px;
                  margin-left: 17px;
                  margin-bottom: 16px;
                "
                @click="viewIframe(item.url)"
              />
              <img
                v-else
                :src="item.icon_url"
                style="
                  cursor: pointer;
                  width: 98px;
                  max-height: 98px;
                  margin-left: 17px;
                  margin-bottom: 16px;
                "
              />
              <p class="fileName">{{ item.name }}</p>
              <p class="createTime">{{ item.create_time }}</p>
            </div>
          </a-tooltip>
        </div>
      </div>
    </a-checkbox-group>
    <div style="display: flex; align-items: center; justify-content: end">
      <a-pagination
        v-model:current="listQuery.pageNo"
        v-model:pageSize="listQuery.pageSize"
        :show-size-changer="pagination.showSizeChanger"
        :pageSizeOptions="pagination.pageSizeOptions"
        :total="pagination.total"
        :showTotal="pagination.showTotal"
        :disabled="pagination.total == 0"
        @change="handleTableChange"
      />
    </div>
    <a-modal
      v-model:open="visibleOffice"
      width="100%"
      style="height: 100vh"
      wrap-class-name="full-modal"
      :footer="null"
    >
      <iframe :src="officeUrl" frameborder="0" width="100%" height="100%"></iframe>
    </a-modal>
    <a-modal
      v-model:open="visibleIframe"
      width="1000px"
      style="height: 1200px"
      :footer="null"
      class="iframe_modal"
    >
      <iframe :src="iframeUrl" frameborder="0" scrolling="no" width="100%" height="100%"></iframe>
    </a-modal>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, onMounted, ref } from 'vue'
import {
  Row,
  Col,
  Modal,
  Divider,
  Image,
  Drawer,
  Switch,
  InputNumber,
  Tooltip,
  RangePicker,
  Upload,
  Empty,
  Pagination
} from 'ant-design-vue'
import {
  SyncOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  DownOutlined
} from '@ant-design/icons-vue'
import { getLogList, getAllServerList, delFileBatch, getAllCateList } from '@/api/file'
import { useRouter } from 'vue-router'
import { requestFailed, requestSuccess } from '@/utils/feedback'
import { getRangeDateTime, inArray, copyText } from '@/utils/common'
import dayjs, { Dayjs } from 'dayjs'

export default defineComponent({
  name: 'FileList',
  components: {
    Empty,
    SyncOutlined,
    PlusOutlined,
    DownOutlined,
    EditOutlined,
    DeleteOutlined,
    [Upload.name]: Upload,
    [Pagination.name]: Pagination,
    [Row.name]: Row,
    [RangePicker.name]: RangePicker,
    [Tooltip.name]: Tooltip,
    [Drawer.name]: Drawer,
    [Switch.name]: Switch,
    [InputNumber.name]: InputNumber,
    [Modal.name]: Modal,
    [Col.name]: Col,
    [Image.name]: Image,
    [Divider.name]: Divider
  },
  setup() {
    const formRef = ref()
    const router = useRouter()
    const dateFormat = 'YYYY-MM-DD HH:mm:s'
    const state = reactive<any>({
      loading: true,
      drawerShow: false,
      picPreviewVisible: false,
      visibleOffice: false,
      visibleIframe: false,
      iframeUrl: '',
      officeUrl: '',
      picPreview: {},
      rangePresets: [
        { label: '近 7 天', value: [dayjs().add(-7, 'd'), dayjs()] },
        { label: '近 14 天', value: [dayjs().add(-14, 'd'), dayjs()] },
        { label: '近 30 天', value: [dayjs().add(-30, 'd'), dayjs()] },
        { label: '近 90 天', value: [dayjs().add(-90, 'd'), dayjs()] },
        { label: '近 180 天', value: [dayjs().add(-180, 'd'), dayjs()] }
      ],
      dataList: {
        data: []
      },
      selectedRowKeys: [],
      selectedKeysPage: {},
      allServer: [],
      allCate: [],
      listQuery: {
        pageNo: 1,
        pageSize: 30,
        ps_id: '',
        send_time_range: [],
        send_time_ranges: [],
        title: ''
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      pagination: {
        pageSizeOptions: ['30', '50', '70'],
        showSizeChanger: true,
        total: 1,
        showTotal: (total) => `总文件数: ${total} `,
        pageSize: 30
      }
    })
    onMounted(() => {
      getRangeDaySingle('')
      getServerDataList()
    })
    function getRangeDaySingle(operate) {
      let end = ''
      let start = ''
      end = getRangeDateTime(0)
      start = end
      start = getRangeDateTime(-7)
      state.listQuery.send_time_range = ref<[Dayjs, Dayjs]>([
        dayjs(start, dateFormat),
        dayjs(end, dateFormat)
      ])
      if (operate == 'auto') {
        setTimeout(() => {
          getDataList()
        }, 1000)
      } else {
        getDataList()
      }
    }

    function handleTableChange(page, pageSize) {
      state.loading = true
      state.pagination.pageSize = pageSize
      state.listQuery.pageSize = pageSize
      state.listQuery.pageNo = page
      getDataList()
    }
    function copyImgUrl() {
      var urlList = ''
      for (let index = 0; index < state.dataList.data.length; index++) {
        const element = state.dataList.data[index]
        if (inArray(element._id, state.selectedRowKeys)) {
          if (urlList.length == 0) {
            urlList = element.url
          } else {
            urlList += urlList + ',' + element.url
          }
        }
      }
      copyText(urlList)
    }
    function handleRemove(e) {
      console.log(e)
      return false
    }

    function reloadList() {
      state.loading = true
      state.listQuery.pageNo = 1
      state.pagination.current = 1
      getRangeDaySingle('')
    }

    function searchSubmit() {
      state.loading = true
      state.listQuery.pageNo = 1
      state.pagination.current = 1
      getDataList()
    }
    function viewOffice(url) {
      state.officeUrl = 'https://view.officeapps.live.com/op/view.aspx?src=' + url
      state.visibleOffice = true
    }
    function viewIframe(url) {
      state.iframeUrl = url
      state.visibleIframe = true
    }

    function getDataList() {
      state.listQuery.send_time_ranges[0] = state.listQuery.send_time_range[0].format(dateFormat)
      state.listQuery.send_time_ranges[1] = state.listQuery.send_time_range[1].format(dateFormat)
      getLogList(state.listQuery).then((res) => {
        state.loading = false
        state.dataList = res
        state.pagination.total = res.totalCount
      })
    }
    function getServerDataList() {
      getAllServerList({}).then((res) => {
        state.allServer = res
      })
      getAllCateList({}).then((res) => {
        state.allCate = res
      })
    }
    async function downloadFile(url, fileName) {
      const response = await fetch(url)
      const blob = await response.blob()
      const blobUrl = URL.createObjectURL(blob)

      const link = document.createElement('a')
      link.href = blobUrl
      link.download = fileName
      link.click()

      URL.revokeObjectURL(blobUrl)
    }

    function downloadSelect() {
      for (let index = 0; index < state.dataList.data.length; index++) {
        const element = state.dataList.data[index]
        if (inArray(element._id, state.selectedRowKeys)) {
          downloadFile(element.url, element.name)
        }
      }
    }
    function copyImgHtml() {
      var urlList = ''
      for (let index = 0; index < state.dataList.data.length; index++) {
        const element = state.dataList.data[index]
        if (inArray(element._id, state.selectedRowKeys)) {
          var imgHtml = ''
          if (element.file_type == 'img') {
            imgHtml = '<img src="' + element.url + '" />'
          }
          urlList += urlList + imgHtml
        }
      }
    }
    function unSelect() {
      state.selectedRowKeys = []
    }
    function SelectAll() {
      for (let i = 0; i < state.dataList.data.length; i++) {
        const element = state.dataList.data[i]
        if (!inArray(element['_id'], state.selectedRowKeys)) {
          state.selectedRowKeys.push(element['_id'])
        }
      }
    }
    function deleteSelect() {
      Modal.confirm({
        title: '确认批量删除所选项?',
        okType: 'danger',
        okText: '确认删除',
        onOk() {
          delFileBatch({ ids: state.selectedRowKeys })
            .then((res) => {
              if (res.code === 200) {
                state.loading = true
                reloadList()
                requestSuccess(res)
              } else {
                requestFailed(res)
              }
            })
            .finally(() => {
              state.selectedRowKeys = []
            })
        }
      })
    }
    return {
      ...toRefs(state),
      handleTableChange,
      reloadList,
      searchSubmit,
      copyImgHtml,
      downloadSelect,
      SelectAll,
      deleteSelect,
      formRef,
      unSelect,
      viewOffice,
      viewIframe,
      inArray,
      router,
      copyImgUrl,
      handleRemove,
      getDataList
    }
  }
})
</script>

<style lang="less">
.full-modal {
  .ant-modal {
    max-width: 100%;
    top: 0;
    padding-bottom: 0;
    margin: 0;
  }
  .ant-modal-content {
    display: flex;
    flex-direction: column;
    height: calc(100vh);
  }
  .ant-modal-body {
    flex: 1;
  }
}
.fileItem {
  position: relative;
  width: 155px;
  max-height: 210px;
  border-radius: 5px;
  padding: 10px;
  margin: 12px;
}
.fileItem:hover {
  background-color: rgb(245, 245, 246);
}
.fileList {
  display: flex;
  width: 100%;
  flex-direction: row;
  flex-wrap: wrap;
}
.fileName {
  width: 141px;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #25262b;
  margin: 0px;
  margin-top: 12px;
  height: 22px;
}
.createTime {
  width: 100%;
  font-size: 12px;
  color: #25262b5c;
  max-width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.div_selected {
  border: 1px solid #1677ff;
  background-color: #f5f5f6;
}
.div_unselected {
  border: 1px solid #ffffff;
}
.ant-modal-wrap.full-modal .ant-modal-close {
  background: #1890ff;
  border-radius: 28px;
  color: #fff;
}
.iframe_modal {
  height: 700px;
  .ant-modal-content {
    height: 700px;
  }
  .ant-modal-body {
    height: 700px;
  }
}
</style>
